package com.stark.wechat.context;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 配置文件读取工具。
 * <pre>
 * 需要在 spring 配置文件中配置 bean ，并在 locations 属性中引入配置文件：
 * 
 * &lt;bean id="propertyUtil" class="com.eastsoft.context.PropertyUtil">
 *     &lt;constructor-arg name="encoding" value="GBK" />&lt;!-- 默认 UTF-8 -->
 *     &lt;property name="locations">
 *         &lt;list>
 *             &lt;value>classpath:config.properties&lt;/value>
 *         &lt;/list>
 *     &lt;/property>
 * &lt;/bean>
 * </pre>
 * @author Ben
 * @since 1.0.0
 * @version 1.0.1, 2017/9/22
 */
public class PropertyUtil extends PropertyPlaceholderConfigurer {
	private static Map<String, String> paramMap = new HashMap<>();
	
	public PropertyUtil() {
		this.setIgnoreResourceNotFound(true);
		this.setFileEncoding("UTF-8");
	}
	
	public PropertyUtil(String encoding) {
		this.setIgnoreResourceNotFound(true);
		this.setFileEncoding(encoding);
	}

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		String key, value;
		for (Entry<Object, Object> entry : props.entrySet()) {
			key = (String) entry.getKey();
			value = (String) entry.getValue();
			paramMap.put(key, value);
		}
	}

	/**
	 * 获取属性值。
	 * @param key 属性名。
	 * @return 属性值。
	 */
	public static String getProperty(String key) {
		final String value = paramMap.get(key);
		return value;
	}
}
